package com.fhz.mvvm.util;

import androidx.annotation.NonNull;

import com.fhz.mvvm.callback.LiveDataCallAdapterFactory;
import com.fhz.mvvm.cons.Cons;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 时间:2023/8/17
 *
 * @author Mr.Feng
 * 简述: 远程请求管理
 * 单例
 */
public class RetrofitMananger {

    private static volatile RetrofitMananger retrofitMananger;

    private Retrofit mRetrofit;
    private RetrofitMananger() {
    }

    public static RetrofitMananger getInstance() {
        if (retrofitMananger == null) {
            synchronized (RetrofitMananger.class) {
                if (retrofitMananger == null) {
                    retrofitMananger = new RetrofitMananger();
                }
            }
        }
        return retrofitMananger;
    }

    public Retrofit getRetrofit() {
        if(mRetrofit == null){
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(Cons.BASE_URL)
                    .client(getOkHttpClint())
                    .addConverterFactory(GsonConverterFactory.create()) //把字符串,变成对象bean
                    .addCallAdapterFactory(new LiveDataCallAdapterFactory()) //把okhttp的 callback 变成 rxjava的obervo  //实体类
                    .build();
        }
        return mRetrofit;
    }

    @NonNull
    private OkHttpClient getOkHttpClint() {
        return new OkHttpClient().newBuilder()
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
    }

}
